<?php
/*
SLS PHP (Simple Localization System PHP library)
---------
New BSD License. Copyright (c) 2007, Brian McConnell

Credits
---------
Initial Concept suggested by Chris Messina (chris@citizenagency.com)
Design by Brian S McConnell
Initial PHP code developed by H Gregory (hbgnyc@mac.com),
PHP implementation by Svetlana Avdey aka ASPa (sveta@metalinkltd.com)
*/


/**
 * Sls class, consist methods to localisate interface
 *
 * @author ASPa
 * @version 0.1
 * @access public
 */
class Sls {
	
	/*
	 * Sls class constructor
	 */
	function Sls() {
		require_once(dirname(__FILE__).'/config.inc');
		$this->localLangs = $this->getLocalLangs();
		$this->setCurrentLang();
	}

    /**
     * method set current localisation language
     *
     * @param string $locale loalisation language code
	 * @access public
	 */
	function setCurrentLang($locale = "") {
		if(!isset($_SESSION)) session_start();
		if (!isset($_SESSION['currentlocale'])) session_register();
		//no param, no session param, but have cookie
		if (!$locale ) {
			if (isset($_SESSION['currentlocale']) && ($this->currlocale = $_SESSION['currentlocale']) ) {
				setcookie('currentlocale', $this->currlocale, time() + YEAR, '/');
			} elseif(isset($_COOKIE["currentlocale"]) && $this->currlocale = $_COOKIE["currentlocale"] ) {
				$_SESSION['currentlocale'] = $this->currlocale;
			} else {
				$this->currlocale = $this->default;
				$_SESSION['currentlocale'] = $this->currlocale;
				setcookie('currentlocale', $this->currlocale, time() + YEAR, '/');
			}
		} elseif( $locale ) {
			$this->currlocale = $locale;
			$_SESSION['currentlocale'] = $this->currlocale;
			setcookie('currentlocale', $this->currlocale, time() + YEAR, '/');
		}
	}
	
    /**
     * method to translate interface element.
     *
	 * @author H Gregory, ASPa
     * @param string $tag token id
     * @param string $text default text. Returns if no translation value found
     * @param string $locale translation language code
     * @param string $escape return translatable token or no (default: translatable)
	 * @access public
	 */
	function gt($tag,$text = '',$locale = null, $escape = false) {
		if ($locale){
			$this->currlocale = $locale;
		}
		if (file_exists($this->sls_dir.'sls/'.$this->currlocale.'/'.$tag.'.html')) {
			$text = file_get_contents($this->sls_dir.'sls/'.$this->currlocale.'/'.$tag.'.html');
			$text = $this->prepareOutText($text);
			if ($escape)
				return $text;
			else	
				return "<span id='".$tag."' class='local_text' name='".$tag."' >".$text."</span>";
		} else {
			if (file_exists($this->sls_dir.'sls/'.$this->currlocale.'/'.$tag.'.html')) {
				$text = file_get_contents($this->sls_dir.'sls/'.$this->currlocale.'/'.$tag.'.html');
				$text = $this->prepareOutText($text);
				if ($escape)
					return $text;
				else
					return "<span id='".$tag."' class='local_text' name='".$tag."' >".$text."</span>";
			} else {
				if (file_exists($this->sls_dir.'sls/'.$this->default.'/'.$tag.'.html')) {
					$text = file_get_contents($this->sls_dir.'sls/'.$this->default.'/'.$tag.'.html');
					$text = $this->prepareOutText($text);
					if ($escape)
						return $text;
					else
						return "<span id='".$tag."' class='local_text' name='".$tag."' >".$text."</span>";
				} else {
					if ($text) {
						if ($escape)
							return $this->prepareOutText($text);
						else
							return "<span id='".$tag."' class='local_text' name='".$tag."' >".$text."</span>";
					} else {
						return "ERROR:  token('".$tag."') not found";
					}
				}
			}
		}
	}
	
    /**
     * method text translatable
     *
     * @param string $text text wich can be translatable
     * @param string $id translation token id for this text
	 * @access private
	 */
	function setTranslatable($text, $id) {
		return "<span id='".$id."' class='static_text' >".$text."</span>";
	}
		
    /**
     * method returns current localisation laguage
     *
	 * @access public
	 */
	function getLocale(){
		return $this->currlocale;
	}
	
    /**
     * method to save token translation in current localisation
     *
     * @param string $tag token id
     * @param string $text translation
     * @param string $locale translation language code
	 * @access public
	 */
	function localeText($tag, $text, $locale = null) {
		$text = $this->prepareInText($text);
		$locale = ($locale != null && !empty($loacle)) ? $locale : $this->getLocale();
		if (!empty($tag) && !empty($text) && !empty($locale)) {
			if ( !is_dir($this->sls_dir.'sls/'.$locale) ) {
				if (!mkdir($this->sls_dir.'sls/'.$locale, 0777)) {
					return false;
				}
			}
			$locale = ($locale != '' && $locale != null) ? $locale : $this->currlocale;
			if ( $fhandle = @fopen($this->sls_dir.'sls/'.$locale.'/'.$tag.'.html', 'w+') ) {
		    	fwrite($fhandle, $text);
		    	fclose($fhandle);
		    	return true; 
			}
			return false;
		} else {
			return false;
		}
	}

    /**
     * method to prepare translation for saving
     * delete all php and html tags (but <a> and <p> tags)
     * 
     * @param string $text translation
	 * @access public
	 */
	function prepareInText( $text = "" ) {
		if ( empty($text) )
			return $text;
			
		$search = array ("/<script.*?>(.*?)<\/script>/si",  // drop javaScript
							);
		$replace = array ("");
		
		$text = preg_replace($search, $replace, $text);
		return trim(strip_tags($text, '<p><a>'));
	}
	
    /**
     * method prepare translation text for displaying in UI
     * it calls in gt function
     *
     * @param string $text displaying text
	 * @access public
	 */
	function prepareOutText( $text = "" ) {
		return nl2br($text);
	}
	
    /**
     * method to get all accessible localisation languages
     * the first rows in return array is prefered languages for user browser
     *
     * @return array
	 * @access public
	 */
	function getLocalLangs() {
		$langs = strtolower($_SERVER['HTTP_ACCEPT_LANGUAGE']);
		$langs = explode(',', $langs);
		$q = 1;
		$result = array();
		foreach ($langs as $lang) {
			if (($qPos = strpos($lang, ';q='))) {
				$q = (float) trim(substr($lang, $qPos+3));
				$lang = substr($lang, 0, $qPos);
			}
			$lang = trim($lang);
			$lang = substr($langs[0], 0,2);
			$result[$lang] = $this->shortLanguages[$lang];
		}
		return array_merge($result, $this->shortLanguages);
    }
	
}

/**
 * JsHelper class, neads to json support
 *
 * @version 0.1
 * @access public
 */
class JsHelper {
	var $q = "'";
	function json($s, $q="\"") {
		$result = 'null'; 
		if(is_numeric($s)) 
			$result = $s;
		if(is_string($s)) {
			$s = str_replace("\"","\\\"",$s);
			$result = $q . preg_replace("/([\1-\037])/e", "sprintf('\\\\u%04X',ord('$1'))", str_replace("\0", '\u0000', $s)) . $q;  
		}
		if($s===false) 
			$result = 'false';
		if($s===true) 
			$result = 'true';
		if(is_array($s)) {
			$c=0;
			if (array_keys($s) !== range(0, sizeof($s)-1)) {
				foreach($s as $k=>$v) 
					$s[$k] = $this->json((string)$k).':'.$this->json($v);
				$result = '{'.join(',', $s).'}';
			} else {
				$result = '[' . join(',', array_map('json', $s)) . ']';
			}
		}
		return $result;
	} 
}

?>